package com.yupi.springbootinit.datasource;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.model.entity.Picture;
import com.yupi.springbootinit.service.PictureService;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 图片获取接口 实现
 */
@Service
public class PictureDataSource implements DataSource<Picture> {
    /**
     * 图片搜索
     *
     * @param searchText 关键词
     * @param pageNum    第几页
     * @param pageSize   每页几条
     * @return
     */
    @Override
    public Page<Picture> doSearch(String searchText, long pageNum, long pageSize) {
        List<Picture> pictures = new ArrayList<>();

        try {
            long current = (pageNum - 1) * pageSize;
            // 这里关键词需要转码, 不转码会报错
            String url = "https://cn.bing.com/images/search?q=" + URLEncoder.encode(searchText, "UTF-8") + "&first=" + current;
            Document doc = Jsoup.connect(url).get();

            // 取出最近的父div
            Elements elements = doc.select(".iuscp.isv");
            // 遍历图片列表所有元素
            for (Element element : elements) {
                // 拿指定长度的数据, 还能防爬虫
                if (pictures.size() > pageSize) {
                    break;
                }

                // TODO 取单个图片数据
                // 取地址json
                String m = element.select(".iusc").get(0).attr("m");
                // 取标题
                String title = element.select(".inflnk").get(0).attr("aria-label");

                // 取出最终图片地址
                Map<String, Object> map = JSONUtil.toBean(m, Map.class); // json字符串转map
                String murl = (String) map.get("murl");

                Picture picture = new Picture();
                picture.setTitle(title);
                picture.setUrl(murl);
                pictures.add(picture);
            }
        } catch (IOException e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "数据获取异常");
        }

        Page<Picture> picturePage = new Page<>(pageNum, pageSize);
        picturePage.setRecords(pictures); // 设置分页的records 集合 => ( result: {data: records:[] }, ... )

        return picturePage;
    }
}
